package com.chatroom.controller;

import com.chatroom.dto.UserDTO;
import com.chatroom.model.PrivateChatRoom;
import com.chatroom.model.User;
import com.chatroom.service.PrivateChatRoomService;
import com.chatroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private final UserService userService;
    private final PrivateChatRoomService privateChatRoomService;

    @Autowired
    public UserController(UserService userService, PrivateChatRoomService privateChatRoomService) {
        this.userService = userService;
        this.privateChatRoomService = privateChatRoomService;
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        
        if (userService.existsByUsername(username)) {
            Map<String, String> response = new HashMap<>();
            response.put("error", "用户名已存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        User user = userService.registerUser(username, password);
        return ResponseEntity.status(HttpStatus.CREATED).body(new UserDTO(user));
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        
        if (userService.validateUser(username, password)) {
            Optional<User> userOpt = userService.findByUsername(username);
            return ResponseEntity.ok(new UserDTO(userOpt.get()));
        } else {
            Map<String, String> response = new HashMap<>();
            response.put("error", "用户名或密码错误");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    @GetMapping("/info/{userId}")
    public ResponseEntity<?> getUserById(@PathVariable Long userId) {
        Optional<User> userOpt = userService.findById(userId);
        
        if (userOpt.isPresent()) {
            return ResponseEntity.ok(new UserDTO(userOpt.get()));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/search")
    public ResponseEntity<?> searchUsers(@RequestParam String query) {
        List<UserDTO> users = userService.getAllUsers().stream()
                .filter(user -> user.getUsername().contains(query))
                .map(UserDTO::new)
                .collect(Collectors.toList());
        return ResponseEntity.ok(users);
    }

    @PostMapping("/{userId}/friends/{friendId}")
    public ResponseEntity<?> addFriend(@PathVariable Long userId, @PathVariable Long friendId) {
        Optional<User> userOpt = userService.findById(userId);
        Optional<User> friendOpt = userService.findById(friendId);
        
        if (userOpt.isPresent() && friendOpt.isPresent()) {
            User user = userOpt.get();
            User friend = friendOpt.get();
            
            // 添加好友关系
            userService.addFriend(user, friend);
            
            // 创建私聊房间
            PrivateChatRoom privateChatRoom = privateChatRoomService.getOrCreatePrivateChatRoom(user, friend);
            logger.info("为用户 {} 和 {} 创建私聊房间，房间号: {}", 
                    user.getUsername(), friend.getUsername(), privateChatRoom.getRoomCode());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("privateChatRoomCode", privateChatRoom.getRoomCode());
            
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/{userId}/friends")
    public ResponseEntity<?> getFriends(@PathVariable Long userId) {
        Optional<User> userOpt = userService.findById(userId);
        
        if (userOpt.isPresent()) {
            List<UserDTO> friends = userService.getFriends(userOpt.get()).stream()
                    .map(UserDTO::new)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(friends);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
} 